import { defineStore } from 'pinia'
import { ref } from 'vue'
import { loginAPI } from '@/api/login'

import { useCartStore } from './carStore'
import { mergeCartAPI } from '@/api/cart'

interface objIn {
    account:any;
    password:any
}

export const useUserInfoStore = defineStore('user',() =>{
    // 1.定义存储用户数据的state
    const cartStore = useCartStore()
    const userInfo =  ref<any>({})
    
    const getUserInfo = async ({account,password}:objIn)=>{
        const res:any = await loginAPI({account,password})
        console.log(res)
        userInfo.value =  res.result
        // 合并购物车操作
        mergeCartAPI(cartStore.cartList.map((item:any) =>{
            return{
                skuId:item.skuId,
                selected:item.selected,
                count:item.count
            }
        }))
        cartStore.updateNewList()
    }
   
    // 退出时清空用户信息
    const clearUserInfo = () =>{
        userInfo.value = {}
        // 执行清除购物车的 action
        cartStore.clearCart()
    }
    // 以对象形式返回state属性和action方法
    return {
        userInfo,
        getUserInfo,
        clearUserInfo
    }
},{
    persist:true
})